/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.weixin_app_tools.main;

import com.seari.weixin_app_tools.bean.DataConfig;
import com.seari.weixin_app_tools.bean.EmptyStringCell;
import com.seari.weixin_app_tools.bean.Person;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Rainbow
 */
public class KaoqinCounter implements Runnable
{
    protected static Logger logger = LoggerFactory.getLogger(KaoqinCounter.class);
    private DataConfig dataConfig;
    private Workbook workbook;
    private List<Person> originList = new ArrayList<>();
    
    public KaoqinCounter(DataConfig config,Workbook workbook)
    {
        this.dataConfig = config;
        this.workbook = workbook;
    }
    
    @Override
    public void run()
    {
        try
        {
            Sheet sheet = workbook.getSheetAt(dataConfig.getSheetNum());
            for(int i = dataConfig.getDataStartLineNum(); i <= dataConfig.getDataEndLineNum() ; i++)//仅读取起始至结尾的表格数据
            {
                Person person = new Person();
                Row row = sheet.getRow(i);
                try
                {
                    convertRowDataToPerson(row, person);
                } catch (Exception e)
                {
                    logger.warn("exception occured at row num:{}  ,message:{}.>>>>>>continue>>>>>>>",i + 1,e.getMessage());
                    e.printStackTrace();
                    continue;
                }
                originList.add(person);
            }
            logger.info("originList size:{}",originList.size());
            //数据统计
            countDataAndWriteToFile();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    //转换行数据至Person实体类
    private void convertRowDataToPerson(Row row,Person person)throws Exception
    {
        //字段须包含company,name,isHealthy,isSeparated,loginTime,loginAddress,isOnBusiness,businessAddress,isAthome
        for(int i = 0; i < dataConfig.getColumnStrings().length; i++)
        {
            Cell cell = row.getCell(i);
            if(cell != null)
            {
                //强制单元格为String类型数据
                cell.setCellType(CellType.STRING);
            }else{
                //单元格为null时，强制单元格为自定义空字符串单元格
                cell = new EmptyStringCell();
            }
            switch(dataConfig.getColumnStrings()[i])
            {
                case "company"://公司名称
                    person.setCompany(cell.getStringCellValue());
                    break;
                case "name"://员工姓名
                    person.setName(cell.getStringCellValue());
                    break;
                case "isHealthy"://健康状况
                    String healthyString = cell.getStringCellValue();
                    if("是".equals(healthyString))
                    {
                        person.setIsHealthy(true);
                    }else{
                        person.setIsHealthy(false);
                    }
                    break;
                case "isSeparated"://是否隔离
                    String separatedString = cell.getStringCellValue();
                    if("是".equals(separatedString))
                    {
                        person.setIsSeparated(true);
                    }else{
                        person.setIsSeparated(false);
                    }
                    break;
                case "loginTime"://打卡时间
                    person.setLoginTime(cell.getStringCellValue());
                    break;
                case "loginAddress"://打卡地点
                    person.setLoginAddress(cell.getStringCellValue().replace(" ", "").trim());
                    break;
                case "isOnBusiness"://是否出差
                    String isOnBusinessString = cell.getStringCellValue();
                    if("是".equals(isOnBusinessString))
                    {
                        person.setIsOnBusiness(true);
                    }else{
                        person.setIsOnBusiness(false);
                    }
                    break;
                case "businessAddress"://出差地
                    person.setBusinessAddress(cell.getStringCellValue());
                    break;
                case "isAthome"://是否居家办公
                    String isAthomeString = cell.getStringCellValue();
                    if("是".equals(isAthomeString))
                    {
                        person.setIsAthome(true);
                    }else{
                        person.setIsAthome(false);
                    }
                    break;
                default:
                    break;
            }
        }
    }
    
    //数据统计
    private void countDataAndWriteToFile() throws IOException
    {
        //各地考勤计数
        int shanghaiKaoqinNum = 0;
        int hubeiKaoqinNum = 0;
        int guangdongKaoqinNum = 0;
        int zhejiangKaoqinNum = 0;
        int beijingKaoqinNum = 0;
        int henanKaoqinNum = 0;
        int otherKaoqinNum = 0;
        //各地出差考勤计数
        int shanghaiOnBusinessKaoqinNum = 0;
        int hubeiOnBusinessKaoqinNum = 0;
        int guangdongOnBusinessKaoqinNum = 0;
        int zhejiangOnBusinessKaoqinNum = 0;
        int beijingOnBusinessKaoqinNum = 0;
        int henanOnBusinessKaoqinNum = 0;
        int otherOnBusinessKaoqinNum = 0;
        outer:
        for(int i = 0; i < originList.size(); i++)
        {
            Person person = originList.get(i);
            //此条数据是否成功被计数
            boolean countFlag = false;
            //上海考勤计数与在上海出差员工计数
            for(String str : dataConfig.getShanghaiFilterStrings())
            {
                //上海考勤员工计数
                if((person.getLoginAddress().contains(str) || person.getLoginAddress().contains("N/A") || StringUtils.isBlank(person.getLoginAddress())) && !person.getIsOnBusiness())
                {
                    shanghaiKaoqinNum++;
                    countFlag = true;
                    continue outer;
                }
                //上海出差员工计数
                else if((person.getLoginAddress().contains(str) || person.getLoginAddress().contains("N/A") || StringUtils.isBlank(person.getLoginAddress())) && person.getIsOnBusiness())
                {
                    shanghaiOnBusinessKaoqinNum++;
                    countFlag = true;
                    continue outer;
                }
            }
            
            //湖北考勤计数与湖北出差员工计数
            for (String str : dataConfig.getHubeiFilterStrings())
            {
                //湖北考勤计数
                if(person.getLoginAddress().contains(str) && !person.getIsOnBusiness())
                {
                    hubeiKaoqinNum++;
                    countFlag = true;
                    continue outer;
                }
                //湖北出差计数
                else if(person.getLoginAddress().contains(str) && person.getIsOnBusiness())
                {
                    hubeiOnBusinessKaoqinNum++;
                    countFlag = true;
                    continue outer;
                }
            }
            
            //重点疫区地区计数
            for (String str : dataConfig.getOtherImportantAreaFilterStrings())
            {
                //考勤计数
                if(person.getLoginAddress().contains(str) && !person.getIsOnBusiness())
                {
                    switch(str)
                    {
                        case "北京":
                            beijingKaoqinNum++;
                            break;
                        case "广东":
                            guangdongKaoqinNum++;
                            break;
                        case "浙江":
                            zhejiangKaoqinNum++;
                            break;
                        case "河南":
                            henanKaoqinNum++;
                            break;
                        default:
                            break;
                    }
                    countFlag = true;
                    continue outer;
                }
                //出差计数
                else if(person.getLoginAddress().contains(str) && person.getIsOnBusiness())
                {
                    switch(str)
                    {
                        case "北京":
                            beijingOnBusinessKaoqinNum++;
                            break;
                        case "广东":
                            guangdongOnBusinessKaoqinNum++;
                            break;
                        case "浙江":
                            zhejiangOnBusinessKaoqinNum++;
                            break;
                        case "河南":
                            henanOnBusinessKaoqinNum++;
                            break;
                        default:
                            break;
                    }
                    countFlag = true;
                    continue outer;
                }
            }
            if(!countFlag)
            {
                //未计数员工计入其他
                //未出差
                if(!person.getIsOnBusiness())
                {
                    otherKaoqinNum++;
                }else{
                    //出差
                    otherOnBusinessKaoqinNum++;
                }
                countFlag = true;
            }
        }
        //写出文件
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet();
        Row row = sheet.createRow(0);//第一行，建立表头
        FileOutputStream fileOutputStream = null;
        int rowNum = 0; //行号
        try
        {
            row.createCell(0).setCellValue("area"); //区域
            row.createCell(1).setCellValue("checkIn"); //考勤数
            row.createCell(2).setCellValue("evection"); //出差数
            row.createCell(3).setCellValue("checkInRate"); //考勤率
            row.createCell(4).setCellValue("sid"); //排序id
            rowNum++;
            //上海数据
            Row shanghaiRow = sheet.createRow(rowNum);
            shanghaiRow.createCell(0).setCellValue("上海");
            shanghaiRow.createCell(1).setCellValue(shanghaiKaoqinNum+shanghaiOnBusinessKaoqinNum);
            shanghaiRow.createCell(2).setCellValue(shanghaiOnBusinessKaoqinNum);
            shanghaiRow.createCell(3).setCellValue(99);
            shanghaiRow.createCell(4).setCellValue(1);
            rowNum++;
            //湖北数据
            Row hubeiRow = sheet.createRow(rowNum);
            hubeiRow.createCell(0).setCellValue("湖北");
            hubeiRow.createCell(1).setCellValue(hubeiKaoqinNum + hubeiOnBusinessKaoqinNum);
            hubeiRow.createCell(2).setCellValue(hubeiOnBusinessKaoqinNum);
            hubeiRow.createCell(3).setCellValue(100);
            hubeiRow.createCell(4).setCellValue(2);
            rowNum++;
            //北京
            Row beijingRow = sheet.createRow(rowNum);
            beijingRow.createCell(0).setCellValue("北京");
            beijingRow.createCell(1).setCellValue(beijingKaoqinNum + beijingOnBusinessKaoqinNum);
            beijingRow.createCell(2).setCellValue(beijingOnBusinessKaoqinNum);
            beijingRow.createCell(3).setCellValue(100);
            beijingRow.createCell(4).setCellValue(5);
            rowNum++;
            //广东
            Row guangdongRow = sheet.createRow(rowNum);
            guangdongRow.createCell(0).setCellValue("广东");
            guangdongRow.createCell(1).setCellValue(guangdongKaoqinNum + guangdongOnBusinessKaoqinNum);
            guangdongRow.createCell(2).setCellValue(guangdongOnBusinessKaoqinNum);
            guangdongRow.createCell(3).setCellValue(100);
            guangdongRow.createCell(4).setCellValue(6);
            rowNum++;
            //浙江
            Row zhejiangRow = sheet.createRow(rowNum);
            zhejiangRow.createCell(0).setCellValue("浙江");
            zhejiangRow.createCell(1).setCellValue(zhejiangKaoqinNum + zhejiangOnBusinessKaoqinNum);
            zhejiangRow.createCell(2).setCellValue(zhejiangOnBusinessKaoqinNum);
            zhejiangRow.createCell(3).setCellValue(100);
            zhejiangRow.createCell(4).setCellValue(7);
            rowNum++;
            //河南
            Row henanRow = sheet.createRow(rowNum);
            henanRow.createCell(0).setCellValue("河南");
            henanRow.createCell(1).setCellValue(henanKaoqinNum + henanOnBusinessKaoqinNum);
            henanRow.createCell(2).setCellValue(henanOnBusinessKaoqinNum);
            henanRow.createCell(3).setCellValue(100);
            henanRow.createCell(4).setCellValue(8);
            rowNum++;
            //其他地区
            Row otherRow = sheet.createRow(rowNum);
            otherRow.createCell(0).setCellValue("其他地区");
            otherRow.createCell(1).setCellValue(otherKaoqinNum + otherOnBusinessKaoqinNum);
            otherRow.createCell(2).setCellValue(otherOnBusinessKaoqinNum);
            otherRow.createCell(3).setCellValue(100);
            otherRow.createCell(4).setCellValue(4);
            rowNum++;
            //重点防疫地区（北京，广东，河南，浙江之和）
            Row importantRow = sheet.createRow(rowNum);
            importantRow.createCell(0).setCellValue("重点防疫地区");
            importantRow.createCell(1).setCellValue(beijingKaoqinNum + guangdongKaoqinNum + zhejiangKaoqinNum + henanKaoqinNum + beijingOnBusinessKaoqinNum + guangdongOnBusinessKaoqinNum + zhejiangOnBusinessKaoqinNum + henanOnBusinessKaoqinNum);
            importantRow.createCell(2).setCellValue(beijingOnBusinessKaoqinNum + guangdongOnBusinessKaoqinNum + zhejiangOnBusinessKaoqinNum + henanOnBusinessKaoqinNum);
            importantRow.createCell(3).setCellValue(100);
            importantRow.createCell(4).setCellValue(3);
            rowNum++;
            fileOutputStream = new FileOutputStream(new File(dataConfig.getOutputFileName()));
            wb.write(fileOutputStream);
        } catch (Exception e)
        {
            e.printStackTrace();
        }finally{
            if(fileOutputStream != null)
            {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
            workbook.close();
        }
        System.out.println("");
    }

    public DataConfig getDataConfig()
    {
        return dataConfig;
    }

    public void setDataConfig(DataConfig dataConfig)
    {
        this.dataConfig = dataConfig;
    }

    public Workbook getWorkbook()
    {
        return workbook;
    }

    public void setWorkbook(Workbook workbook)
    {
        this.workbook = workbook;
    }

}
